/*
Copyright 2011 Raymond Giorgi

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package edu.pitt.cs3530.threads;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

import edu.pitt.cs3530.configuration.FrontEndConfiguration;
import edu.pitt.cs3530.messages.AbstractMessage;

public class ReceiverThread {

	public static class ReceiveMessage extends Thread {
		private Socket socket = null;

		private ReceiveMessage(Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {
			if (socket != null) {
				while (true) {
					try {
						ObjectInputStream ois = new ObjectInputStream(socket
								.getInputStream());
						AbstractMessage message = (AbstractMessage) ois
								.readObject();
						message.setSocket(socket);
						message.processMessage();
					} catch (IOException e) {
						break;
					} catch (ClassNotFoundException e) {
						break;
					}
				}
			}
		}
	}

	public static class ReceiveConnection extends Thread {
		ServerSocket ss = null;

		@Override
		public void run() {
			try {
				ss = new ServerSocket(FrontEndConfiguration.getInstance()
						.getConnectingPort());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (ss != null) {
				while (true) {
					try {
						Socket socket = ss.accept();
						new ReceiveMessage(socket).start();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
}
